package com.jsoft.controller;

import com.alibaba.fastjson.JSON;
import com.jsoft.entity.Enterprise;
import com.jsoft.service.EnterpriseService;
import com.jsoft.service.impl.EnterpriseServiceImpl;
import com.jsoft.utils.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 企业表的控制层
 * @author snkstart
 * @create 2023-02-20 20:49
 */
@WebServlet("*.en")
public class EnterpriseController extends HttpServlet {
    private EnterpriseService enterpriseService = new EnterpriseServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取servletPath /front/xxx.user
        String servletPath = req.getServletPath();
        // 2.获取到xxx
        String methodName = servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length() - 3);

        try {
            // 3.利用反射获取对应的方法对象
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 4.执行对应的方法
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取企业下拉列表
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("****************");
        PrintWriter writer = resp.getWriter();
        List<Enterprise> enterprises = enterpriseService.selectEnterprise();
        System.out.println(enterprises);
        writer.write(JSON.toJSONString(new ResultUtil("enters", enterprises)));
        writer.flush();
        writer.close();

    }

    protected void selectId(HttpServletRequest req, HttpServletResponse resp) {
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String acquirerName = req.getParameter("acquirerName");
        String acquirerCode = enterpriseService.selectCode(acquirerName);
        writer.write(JSON.toJSONString(new ResultUtil("acquirerCode", acquirerCode)));
        writer.flush();
        writer.close();

    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
